package com.codefalse.mybatis.generator;

import com.codefalse.mybatis.generator.util.SQLiteUtils;
import com.codefalse.mybatis.generator.view.HomeView;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @author songxiangfeng
 * Created At 2019-12-10 14:29
 */
@SpringBootApplication
@Slf4j
public class CodefalseApplication extends AbstractJavaFxApplicationSupport implements ApplicationRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化SQLite工具类
        SQLiteUtils.initJdbcTemplate(jdbcTemplate);

        File dataFile = new File("./data");
        boolean existPath = dataFile.exists();
        if (!existPath) {
            existPath = dataFile.mkdirs();
            log.debug("创建配置信息存放目录：{}", existPath);
        }
        boolean existDB = false;
        if (existPath) {
            File dbFile = new File("./data/codefalse.db");
            existDB = dbFile.exists();
            if (!existDB) {
                existDB = dbFile.createNewFile();
                log.debug("创建配置信息数据库：{}", existDB);
            }
        }
        if (!existDB) {
            throw new Exception("找不到配置信息数据库");
        }
        String projectPath = System.getProperty("user.dir");
        File sqlFile = new File(projectPath + "/sql");
        File[] files = sqlFile.listFiles();
        for (File file : files) {
            log.debug("初始化Sql文件：{}", file.getName());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            is.read(bytes);
            String initSql = new String(bytes);
            String[] initSqlArray = initSql.split(";");
            for (String sql : initSqlArray) {
                jdbcTemplate.execute(initSql);
            }
        }
    }

    public static void main(String[] args) {
        launch(CodefalseApplication.class, HomeView.class, args);
    }
}
